import 'dart:convert';

import 'package:elephant_fish/TRTCChatSalonDemo/ui/list/VoiceRoomCreate.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/has_family_request.dart';
import 'package:elephant_fish/http/request/is_approve_request.dart';
import 'package:elephant_fish/http/request/user_info_request.dart';
import 'package:elephant_fish/model/user.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/page/real_name_authentication_page.dart';
import 'package:elephant_fish/page/real_name_complete.dart';
import 'package:elephant_fish/page/room_manager_page.dart';
import 'package:elephant_fish/page/safe_deposit_box_page.dart';
import 'package:elephant_fish/page/setting_page.dart';
import 'package:elephant_fish/page/share_page.dart';
import 'package:elephant_fish/page/user_personal_interface_page.dart';
import 'package:elephant_fish/page/voice_setting_page.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/IconTextButton.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'bag_page.dart';
import 'family_manager_in_new_page.dart';
import 'family_manager_page.dart';
import 'login_page.dart';
import 'my_level_page.dart';

class IndexMyInfoPage extends StatefulWidget {
  final User user;

  const IndexMyInfoPage({Key key, this.user}) : super(key: key);

  @override
  _IndexMyInfoPageState createState() => _IndexMyInfoPageState();
}

class _IndexMyInfoPageState extends State<IndexMyInfoPage> {
  bool isRealName = false;
  UserInfoEntity userInfoEntity;
  bool canCreateReason = false;
  bool isHasFamily = false;

  @override
  void initState() {
    getInitData();
    hasFamily();
    isApprove();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Color(0xff140c3d),
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Color(0xff140c3d),
        centerTitle: true,
        title: Text(
          '我的',
          style: TextStyle(fontSize: SizeUtil.px(32), color: Color(0xfff5f5f5)),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Stack(
              children: [
                InkWell(
                  onTap: () {
                    // Navigator.pushNamed(context, '/userPersonalInterface');
                    // Navigator.of(context)
                    //     .push(MaterialPageRoute(
                    //         builder: (context) => UpdateInfoPage(
                    //             arguments: {'userInfo': userInfoEntity})))
                    //     .then((value) => {
                    //           if (value == 'refresh') {getInitData()}
                    //         });
                    Navigator.of(context)
                        .push(MaterialPageRoute(
                            builder: (context) => UserPersonalInterfacePage(
                                  userInfoEntity: userInfoEntity,
                                )))
                        .then((value) => {
                              if (value == 'refresh') {getInitData()}
                            });
                  },
                  child: Align(
                    alignment: Alignment.topLeft,
                    child: Padding(
                      padding: EdgeInsets.only(
                          left: SizeUtil.px(20), top: SizeUtil.px(35)),
                      child: Container(
                        width: SizeUtil.px(130),
                        height: SizeUtil.px(130),
                        child: CircleAvatar(
                          radius: SizeUtil.px(35),
                          backgroundImage: NetworkImage(userInfoEntity == null
                              ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                              : userInfoEntity.avatar == ""
                                  ? widget.user.avatar
                                  : 'http://119.28.131.94:82' +
                                      userInfoEntity.avatar),
                        ),
                      ),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(
                        left: SizeUtil.px(178), top: SizeUtil.px(62)),
                    child: Text(
                      userInfoEntity == null
                          ? '还未设置昵称'
                          : userInfoEntity.nickname == ""
                              ? '还未设置昵称'
                              : userInfoEntity.nickname,
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: SizeUtil.px(33), color: Color(0xffffffff)),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                    padding: EdgeInsets.only(
                        left: SizeUtil.px(178),
                        top: SizeUtil.px(110),
                        right: SizeUtil.px(150)),
                    child: Text(
                      userInfoEntity == null
                          ? '还未设置个性签名'
                          : userInfoEntity.signature == ""
                              ? '还未设置个性签名'
                              : userInfoEntity.signature,
                      maxLines: 1,
                      style: TextStyle(
                          fontSize: SizeUtil.px(26), color: Color(0xff818181)),
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: Padding(
                      padding: EdgeInsets.only(
                          right: SizeUtil.px(45), top: SizeUtil.px(84)),
                      child: Icon(
                        Icons.arrow_forward_ios,
                        size: SizeUtil.px(36),
                        color: Color(0xfff3f3f3),
                      )),
                ),
              ],
            ),
            Stack(
              children: [
                Align(
                  alignment: Alignment.topLeft,
                  child: Padding(
                      padding: EdgeInsets.only(
                          left: SizeUtil.px(128), top: SizeUtil.px(30)),
                      child: Column(
                        children: [
                          Text(
                            '粉丝',
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: SizeUtil.px(26),
                                color: Color(0xffffffff)),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Text(
                            userInfoEntity == null
                                ? '0'
                                : userInfoEntity.fans == null
                                    ? '0'
                                    : userInfoEntity.fans.toString(),
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: SizeUtil.px(26),
                                color: Color(0xffffffff)),
                          ),
                        ],
                      )),
                ),
                Align(
                  alignment: Alignment.topRight,
                  child: Padding(
                      padding: EdgeInsets.only(
                          right: SizeUtil.px(128), top: SizeUtil.px(30)),
                      child: Column(
                        children: [
                          Text(
                            '关注',
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: SizeUtil.px(26),
                                color: Color(0xffffffff)),
                          ),
                          SizedBox(
                            height: 10,
                          ),
                          Text(
                            userInfoEntity == null
                                ? '0'
                                : userInfoEntity.attentions == null
                                    ? '0'
                                    : userInfoEntity.attentions.toString(),
                            maxLines: 1,
                            style: TextStyle(
                                fontSize: SizeUtil.px(26),
                                color: Color(0xffffffff)),
                          ),
                        ],
                      )),
                ),
              ],
            ),
            Padding(
              padding:
                  EdgeInsets.only(top: (size.width - SizeUtil.px(710)) / 2),
              child: Container(
                width: size.width - SizeUtil.px(40),
                height: SizeUtil.px(180),
                decoration: BoxDecoration(
                  color: Color(0xff2b244d),
                  borderRadius:
                      BorderRadius.all(Radius.circular(SizeUtil.px(12))),
                ),
                child: Stack(
                  children: [
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                          padding: EdgeInsets.only(
                              left: ((size.width - SizeUtil.px(40)) -
                                      (SizeUtil.px(160) * 4)) /
                                  5,
                              top: SizeUtil.px(6)),
                          child: Container(
                            width: SizeUtil.px(160),
                            child: IconTextButton.icon(
                              icon: Image.asset(
                                'assets/images/my_info_bag.png',
                              ),
                              label: Text(
                                "背包",
                                style: TextStyle(
                                    fontSize: SizeUtil.px(22),
                                    color: Color(0xfff3f3f3)),
                              ),
                              color: Color(0xff2b244d),
                              textColor: Color(0xfff3f3f3),
                              elevation: 1.0,
                              disabledElevation: 0,
                              iconTextAlignment:
                                  IconTextAlignment.iconTopTextBottom,
                              onPressed: () {
                                Navigator.of(context).push(MaterialPageRoute(
                                    builder: (context) => BagPage(userInfoEntity: userInfoEntity,)));
                              },
                            ),
                          )),
                    ),
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                          padding: EdgeInsets.only(
                              top: SizeUtil.px(6),
                              left: (((size.width - SizeUtil.px(40)) -
                                              (SizeUtil.px(160) * 4)) /
                                          5) *
                                      2 +
                                  SizeUtil.px(160)),
                          child: Container(
                            width: SizeUtil.px(160),
                            child: IconTextButton.icon(
                              icon: Image.asset(
                                'assets/images/my_info_level.png',
                              ),
                              label: Text(
                                "等级",
                                style: TextStyle(
                                    fontSize: SizeUtil.px(22),
                                    color: Color(0xfff3f3f3)),
                              ),
                              color: Color(0xff2b244d),
                              textColor: Color(0xfff3f3f3),
                              elevation: 1.0,
                              disabledElevation: 0,
                              iconTextAlignment:
                                  IconTextAlignment.iconTopTextBottom,
                              onPressed: () {
                                Navigator.of(context).push(MaterialPageRoute(
                                    builder: (context) => MyLevelPage(userInfoEntity: userInfoEntity,)));
                              },
                            ),
                          )),
                    ),
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                          padding: EdgeInsets.only(
                              left: (((size.width - SizeUtil.px(40)) -
                                              (SizeUtil.px(160) * 4)) /
                                          5) *
                                      3 +
                                  SizeUtil.px(160) * 2,
                              top: SizeUtil.px(6)),
                          child: Container(
                            width: SizeUtil.px(160),
                            child: IconTextButton.icon(
                              icon: Image.asset(
                                'assets/images/my_info_welfare.png',
                              ),
                              label: Text(
                                "语音房",
                                style: TextStyle(
                                    fontSize: SizeUtil.px(22),
                                    color: Color(0xfff3f3f3)),
                              ),
                              color: Color(0xff2b244d),
                              textColor: Color(0xfff3f3f3),
                              elevation: 1.0,
                              disabledElevation: 0,
                              iconTextAlignment:
                                  IconTextAlignment.iconTopTextBottom,
                              onPressed: () {
                                userInfoEntity != null ? userInfoEntity.noticeRoom != 0 ?
                                Navigator.of(context).push( MaterialPageRoute(builder: (context)=>VoiceSettingPage(userInfoEntity: userInfoEntity,)))
                                :Navigator.of(context).push( MaterialPageRoute(builder: (context)=>VoiceRoomCreatePage(userInfoEntity: userInfoEntity,)))
                                :Navigator.of(context).push( MaterialPageRoute(builder: (context)=>VoiceRoomCreatePage(userInfoEntity: userInfoEntity,)));
                              },
                            ),
                          )),
                    ),
                    Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                          padding: EdgeInsets.only(
                              left: (((size.width - SizeUtil.px(40)) -
                                              (SizeUtil.px(160) * 4)) /
                                          5) *
                                      4 +
                                  SizeUtil.px(160) * 3,
                              top: SizeUtil.px(6)),
                          child: Container(
                            width: SizeUtil.px(160),
                            child: IconTextButton.icon(
                              icon: Image.asset(
                                'assets/images/my_info_share.png',
                              ),
                              label: Text(
                                "邀请",
                                style: TextStyle(
                                    fontSize: SizeUtil.px(22),
                                    color: Color(0xfff3f3f3)),
                              ),
                              color: Color(0xff2b244d),
                              textColor: Color(0xfff3f3f3),
                              elevation: 1.0,
                              disabledElevation: 0,
                              iconTextAlignment:
                                  IconTextAlignment.iconTopTextBottom,
                              onPressed: () {
                                Navigator.of(context).push(MaterialPageRoute(
                                    builder: (context) => SharePage(
                                          userInfoEntity: userInfoEntity,
                                        )));
                              },
                            ),
                            // IconButton(onPressed: (){
                            //   print('邀请');
                            // }, icon: Image.asset('assets/images/my_info_share.png')),
                          )),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
                padding: EdgeInsets.only(
                    left: (size.width - SizeUtil.px(710)) / 2,
                    top: SizeUtil.px(18)),
                child: Container(
                  width: SizeUtil.px(710),
                  height: SizeUtil.px(540),
                  decoration: BoxDecoration(
                      color: Color(0xff2b244d),
                      borderRadius:
                          BorderRadius.all(Radius.circular(SizeUtil.px(12)))),
                  child: Column(
                    children: [
                      Align(
                          alignment: Alignment.topLeft,
                          child: InkWell(
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(27),
                                      top: SizeUtil.px(31)),
                                  child: Image.asset(
                                    'assets/images/my_info_real_name.png',
                                    width: SizeUtil.px(47),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(25),
                                      top: SizeUtil.px(25)),
                                  child: InkWell(
                                    child: Text(
                                      '主播认证',
                                      style: TextStyle(
                                          fontSize: SizeUtil.px(29),
                                          color: Color(0xfff3f3f3)),
                                    ),
                                    onTap: () {
                                      isRealName
                                          ? Navigator.of(context).push(
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      RealNameComplete()))
                                          : Navigator.of(context)
                                              .push(MaterialPageRoute(
                                                  builder: (context) =>
                                                      RealNameAuthenticationPage()))
                                              .then((value) => {
                                                    if (value == 'refresh')
                                                      {isApprove()}
                                                  });
                                    },
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {
                              isRealName
                                  ? Navigator.of(context).push(
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              RealNameComplete()))
                                  : Navigator.of(context)
                                      .push(MaterialPageRoute(
                                          builder: (context) =>
                                              RealNameAuthenticationPage()))
                                      .then((value) => {
                                            if (value == 'refresh')
                                              {isApprove()}
                                          });
                            },
                          )),
                      Align(
                          alignment: Alignment.topLeft,
                          child: InkWell(
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(27),
                                      top: SizeUtil.px(55)),
                                  child: Image.asset(
                                    'assets/images/my_info_room_manager.png',
                                    width: SizeUtil.px(47),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(25),
                                      top: SizeUtil.px(60)),
                                  child: InkWell(
                                    child: Text(
                                      '房间管理',
                                      style: TextStyle(
                                          fontSize: SizeUtil.px(29),
                                          color: Color(0xfff3f3f3)),
                                    ),
                                    onTap: () {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  RoomManagerPage()));
                                    },
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (context) => RoomManagerPage()));
                            },
                          )),
                      Align(
                          alignment: Alignment.topLeft,
                          child: InkWell(
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(27),
                                      top: SizeUtil.px(55)),
                                  child: Image.asset(
                                    'assets/images/my_info_family_manager.png',
                                    width: SizeUtil.px(47),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(25),
                                      top: SizeUtil.px(60)),
                                  child: InkWell(
                                    child: Text(
                                      '家族管理',
                                      style: TextStyle(
                                          fontSize: SizeUtil.px(29),
                                          color: Color(0xfff3f3f3)),
                                    ),
                                    onTap: () {
                                      userInfoEntity == null
                                          ? Navigator.of(context).push(
                                              MaterialPageRoute(
                                                  builder: (context) =>
                                                      FamilyManagerPage()))
                                          : isHasFamily ?
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  FamilyManagerInNewPage(
                                                    id: userInfoEntity.familyId,
                                                  )))
                                          : Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  FamilyManagerPage()));
                                    },
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {
                              userInfoEntity == null
                                  ? Navigator.of(context).push(
                                      MaterialPageRoute(
                                          builder: (context) =>
                                              FamilyManagerPage()))
                                  : isHasFamily ?
                              Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  FamilyManagerInNewPage(
                                                    id: userInfoEntity.familyId,
                                                  )))
                              : Navigator.of(context).push(
                              MaterialPageRoute(
                              builder: (context) =>
                              FamilyManagerPage()));
                            },
                          )),
                      Align(
                          alignment: Alignment.topLeft,
                          child: InkWell(
                            child: Row(
                              children: [
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(27),
                                      top: SizeUtil.px(60)),
                                  child: Image.asset(
                                    'assets/images/my_info_safe_box.png',
                                    width: SizeUtil.px(47),
                                  ),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(
                                      left: SizeUtil.px(25),
                                      top: SizeUtil.px(55)),
                                  child: InkWell(
                                    child: Text(
                                      '保险箱',
                                      style: TextStyle(
                                          fontSize: SizeUtil.px(29),
                                          color: Color(0xfff3f3f3)),
                                    ),
                                    onTap: () {
                                      Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  SafeDepositBoxPage()));
                                    },
                                  ),
                                ),
                              ],
                            ),
                            onTap: () {
                              Navigator.of(context).push(MaterialPageRoute(
                                  builder: (context) => SafeDepositBoxPage()));
                            },
                          )),
                      Align(
                          alignment: Alignment.topLeft,
                          child: InkWell(
                              child: Row(
                                children: [
                                  Padding(
                                    padding: EdgeInsets.only(
                                        left: SizeUtil.px(27),
                                        top: SizeUtil.px(60)),
                                    child: Image.asset(
                                      'assets/images/my_info_setting.png',
                                      width: SizeUtil.px(47),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(
                                        left: SizeUtil.px(25),
                                        top: SizeUtil.px(55)),
                                    child: InkWell(
                                      child: Text(
                                        '设置',
                                        style: TextStyle(
                                            fontSize: SizeUtil.px(29),
                                            color: Color(0xfff3f3f3)),
                                      ),
                                      onTap: () {
                                        Navigator.of(context).push( MaterialPageRoute(builder: (context)=>SettingPage(userInfoEntity: userInfoEntity,)));
                                        // Navigator.of(context).push(
                                        //     MaterialPageRoute(
                                        //         builder: (context) =>
                                        //             VoiceRoomListPage()));
                                      },
                                    ),
                                  ),
                                ],
                              ),
                              onTap: () {
                                Navigator.of(context).push( MaterialPageRoute(builder: (context)=>SettingPage()));
                                // Navigator.of(context).push(MaterialPageRoute(
                                //     builder: (context) => VoiceRoomListPage()));
                              }))
                    ],
                  ),
                ))
          ],
        ),
      ),
    );
  }

  Future<void> getInitData() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = UserInfoRequest();
    request.add('type', 2).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    }
    setState(() {
      userInfoEntity = UserInfoEntity.fromJson(
          new Map<String, dynamic>.from(result['data']));
      prefs.setString('USERINFO', jsonEncode(userInfoEntity));
      print(userInfoEntity);
    });
  }

  isApprove() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = IsApproveRequset();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else if (result['data']['status'] == '已认证') {
      setState(() {
        isRealName = true;
      });
    } else if (result['data']['status'] == '未认证') {
      setState(() {
        isRealName = false;
      });
    }
  }

  Future<void> hasFamily() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = HasFamilyRequest();
    request.addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(arguments: {'loginCode': '-1'},);
        },
      ));
    }else if(result['code'] == 0){

      setState(() {
        isHasFamily = result['data']['hasFamily'];
      });

    }
  }


  void tencentImLogin() {
    // TencentImPlugin.login(userID: userInfoEntity.userId, userSig: GenerateTestUserSig.genTestSig(userInfoEntity.userId));
  }
}
